package com.zh.test.IO;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class IOServer {

        public static void main(String[] args) throws Exception {

            ServerSocket serverSocket = new ServerSocket(8000);
            System.out.println("开始监听8000端口");
            // (1) 接收新连接线程
            new Thread(() -> {
                while (true) {
                    try {
                        // (1) 阻塞方法获取新的连接
                        Socket socket = serverSocket.accept();

                        // (2) 每一个新的连接都创建一个线程，负责读取数据tb_course
                        //todo 这里应该改成线程池,每次从
                        new Thread(() -> {
                            try {
                                byte[] data = new byte[1024];
                                InputStream inputStream = socket.getInputStream();
                                while (true) {
                                    int len;
                                    // (3) 按字节流方式读取数据
                                    while ((len = inputStream.read(data)) != -1) {
                                        String s = new String(data, 0, len);
                                        JSONObject jsonObject = JSONObject.fromObject(s);
                                        System.out.println("topic:"+jsonObject.get("topic")+"|content:"+jsonObject.get("content"));


                                    }
                                }
                            } catch (IOException e) {
                            }
                        }).start();

                    } catch (IOException e) {
                    }

                }
            }).start();
        }

}
